package com.asura.ops.sync.server.monitor;

import com.asura.ops.sync.server.model.entity.vo.ThreadVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: huyuntao(Mars)
 * @date: 2022/11/9
 * @description: 类的描述
 */
@Component
public class ThreadMonitor {

    @Value("${spring.profiles.active}")
    private String env;

    private Set<String> listenServerList = Sets.newHashSet();

    public void addListenServer(String serverName) {
        listenServerList.add(serverName);
    }

    public void removeListenServer(String serverName) {
        listenServerList.remove(serverName);
    }


    private ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(1);

    @PostConstruct
    public void cleanChange() {
        //部署多台，可能出现同时执行，先手动执行清理，后续可以接入JOB
        threadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                checkThreadActive();
            }
        }, 0, 2, TimeUnit.MINUTES);

    }

    /**
     * 检查线程信息
     *
     * @return
     */
    public List<ThreadVo> checkThreadActive() {
        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        int noThreads = currentGroup.activeCount();
        Thread[] lstThreads = new Thread[noThreads];
        currentGroup.enumerate(lstThreads);
        List<ThreadVo> result = Lists.newArrayList();
        for (int i = 0; i < noThreads; i++) {
            ThreadVo threadVo = new ThreadVo();
            threadVo.setThreadNo(lstThreads[i].getId() + "");
            threadVo.setThreadName(lstThreads[i].getName());
            threadVo.setThreadState(lstThreads[i].getState().name());
            result.add(threadVo);
        }
        for (String serverId : listenServerList) {
            List<ThreadVo> list = result.stream().filter(t -> t.getThreadName().contains("-" + serverId + "-")).collect(Collectors.toList());
            if (list.size() == 0) {
                //预警，监听线程停止了
                String msg = String.format("数据同步服务预警：环境【%s】,服务线程【%s】已停止，请检查", env, serverId);

            }
        }
        return result;
    }

}
